<template>
  <div class="square bg-hex-fff">
    <div>
      <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
        <div class="relative">
          <image class="pointer-events-none absolute left-0 right-0 top-0 h-180rpx w-100%"
                 :src="`${cdnUrl1}/imgs/xy/square/bg.png${imgVersion}`" mode="aspectFill" />
          <div class="flex items-center justify-between p-32rpx" :style="{ paddingTop: `${searchBarTop}px` }">
            <span class="text-32rpx font-600 text-hex-212424">广场</span>
            <img :src="`${cdnUrl1}/imgs/xy/square/search.png${imgVersion}`" class="h-48rpx w-48rpx" alt="" srcset="">
          </div>
        </div>
      </div>
      <div v-if="currentTab === 1">
        <div v-if="attentionList && attentionList.length > 0">
          <div v-for="item in attentionList" class="p-36rpx pb-12rpx pt-36rpx">
            <div class="flex items-center justify-between">
              <div class="mr-10rpx flex items-center justify-start">
                <image class="mr-16rpx h-76rpx w-76rpx rounded-50%" :src="item.avatarUrl" mode="scaleToFill" @click.stop="navTo(`/pages-square/my?userId=${item.userId}`)" />
                <div class="mr-16rpx text-28rpx font-500 text-hex-333">
                  {{ item.nickname }}
                </div>
                <div class="text-24rpx text-hex-7C8699">{{ item.createdAt }}</div>
              </div>
            <!-- <div class="mr-13rpx text-60rpx text-hex-ABAFB5">···</div> -->
            </div>
            <div class="relative flex items-center pb-32rpx pt-20rpx" @click.stop="routerTo('/pages-square/articledetail', item.id)">
              <div class="max-h-700rpx w-100% flex items-center justify-center overflow-hidden">
                <image class="w-100% overflow-hidden rounded-30rpx" :src="item.coverImage" mode="widthFix" />
              </div>
              <div v-if="item.articleType===2" class="absolute right-30rpx top-45rpx flex items-center justify-center">
                <image
                  :src="`${cdnUrl}/imgs/square/radio.png${imgVersion}`"
                  mode="widthFix"
                  class="w-60rpx"
                />
              </div>
            </div>
            <div class="flex items-center justify-between">
              <div>
                <img class="h-56rpx w-56rpx" :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" alt="" @click="open">
              </div>
              <div class="flex items-center text-hex-333">
                <img class="h-56rpx w-56rpx"
                     :src="`${cdnUrl}/svgicons/pl_save${item.isCollect ?'true':'false'}.svg${imgVersion}`"
                     alt="" @click.stop="handleClickCollect(item)">
                <text class="ml-10rpx mr-24rpx text-28rpx">{{ item.collectCount }}</text>
                <img class="h-56rpx w-56rpx"
                     :src="`${cdnUrl}/svgicons/pl_like${item.isLike ?'true':'false'}.svg${imgVersion}`"
                     alt="" @click.stop="handleClickLike(item)">
                <text class="ml-10rpx mr-24rpx text-28rpx">{{ item.likeCount }}</text>
                <img class="h-56rpx w-56rpx"
                     :src="`${cdnUrl}/svgicons/pl_msg.svg${imgVersion}`" alt="" @click.stop="routerTo('/pages-square/articledetail', item.id)">
                <text class="ml-10rpx mr-24rpx text-28rpx">{{ item.commentCount }}</text>
              </div>
            </div>
            <div class="mt-32rpx flex items-center justify-between text-30rpx">
              <div class="h-40rpx w-468rpx truncate text-hex-333">{{ item.articleType === 1 ? item.title:item.content }}</div>
              <div class="font-semibold text-hex-7C8699" @click.stop="routerTo('/pages-square/articledetail', item.id)">查看全文</div>
            </div>
          </div>
        </div>
        <div v-else
             class="mt-200rpx flex items-center justify-center">
          <div>
            <image
              class="h-364rpx w-364rpx"
              :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
              mode="scaleToFill"
            />
            <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
          </div>
        </div>
      </div>
      <div v-else-if="currentTab === 2 ">
        <!-- 置顶区  -->
        <div class="relative mb-50rpx flex justify-center">
          <!-- 背景图1 -->
          <image class="absolute left-33rpx top-15rpx" :src="`${cdnUrl1}/imgs/xy/square/Group%206655.png${imgVersion}`" mode="scaleToFill" />
          <image class="absolute right-0 top--15rpx h-156rpx w-174rpx" :src="`${cdnUrl1}/imgs/xy/square/image%20220.png${imgVersion}`" mode="scaleToFill" />
          <div class="relative z-5 mt-96rpx flex justify-center rounded-24rpx"
               style="box-shadow: 0rpx 6rpx 20rpx 0rpx rgb(179 206 186 / 20%), inset 0rpx 0rpx 0rpx 0rpx #FFF;">
            <div v-if="topList.length > 0"
                 class="ml-2rpx box-border h-full w-692rpx border-4rpx border-hex-fff rounded-20rpx border-solid from-[rgba(235,235,235,0.84)] to-hex-fff bg-gradient-to-b px-36rpx pt-16rpx shadow-transparent"
                 style="backdrop-filter:blur(10rpx);background:linear-gradient(to bottom,rgba(242 253 239 / 49%),#F9FEF8,#fff,#fff,#fff);">
              <div v-for="(item, index) in topList" :key="item"
                   class="pb-12rpx" :class="{ 'border-b-1rpx border-b-hex-f5f5f5 border-b-solid': index !== 2 }"
                   @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)">
                <div class="multiLine-hiddle pt-14rpx text-29rpx font-600 leading-4.6 text-hex-333333">
                  {{ item.article_type===1?item.title:item.content }}
                </div>
                <div class="mt-10rpx flex items-center">
                  <text class="mr-10rpx text-22rpx text-hex-abafb5">{{ item.nickname }}</text>
                  <text v-if="item.article_type === 0"
                        class="border-2rpx rounded-8rpx border-solid bg-hex-fef6ff px-10rpx text-20rpx text-hex-FF4E4E">
                    官方
                  </text>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="waterfallList.length===0"
             class="mt-200rpx flex items-center justify-center">
          <div>
            <image
              class="h-364rpx w-364rpx"
              :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
              mode="scaleToFill"
            />
            <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
          </div>
        </div>
        <!-- 置顶区结束 -->
        <div class="mx-16rpx">
          <s-waterfall :datalist="waterfallList" :column="2" @click="cancelMore">
            <template #default="{ item }">
              <div class="relative max-h-500rpx w-328rpx flex items-center justify-center overflow-hidden rounded-24rpx">
                <image class="rounded-24rpx" lazy-load :src="item.imgUrl" mode="widthFix"
                       @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                <div v-if="item.article_type===2" class="absolute right-40rpx top-16rpx flex items-center justify-center">
                  <image :src="`${cdnUrl}/imgs/square/radio.png${imgVersion}`" mode="widthFix" class="w-60rpx"
                         @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                </div>
              </div>
              <div class="multiLine-hiddle mt-10rpx w-320rpx text-30rpx">
                {{ item.article_type===1?item.title:item.content }}
              </div>
              <div class="mb-22rpx w-320rpx flex items-center justify-between">
                <div class="flex items-center text-24rpx">
                  <image class="mr-15rpx h-36rpx w-36rpx rounded-50%" :src="item.avatar_url" mode="scaleToFill" />
                  <text>{{ item.nickname }}</text>
                </div>
                <div class="flex justify-center text-right text-hex-ABAFB5" @click.stop="handleClickMore(item)">
                  <image :src="`${cdnUrl}/imgs/square/more.png${imgVersion}`" mode="widthFix" class="h-48rpx w-48rpx" />
                </div>
              </div>
              <div v-show="currPoint === item.user_article__id && isShowPoint" class="relative">
                <div class="absolute bottom-80rpx left-0 z-99 box-border h-66rpx w-336rpx flex items-center justify-between rounded-lg bg-hex-fff px-16rpx text-hex-333"
                     style="box-shadow: 0 4px 20px 0 rgb(0 0 0 / 5%);">
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_like${isLike}.svg${imgVersion}`"
                         alt="" mode="scaleToFill" @click.stop="handleClickLike1(item)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_save${isCollect}.svg${imgVersion}`"
                         alt="" mode="scaleToFill" @click.stop="handleClickCollect1(item)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_msg.svg${imgVersion}`" mode="scalitemeToFill" alt=""
                         @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" mode="scaleToFill" alt="" @click.stop="routerTo1('/pages-square/articledetail', item.user_article__id, true)" />
                </div>
              </div>
            </template>
          </s-waterfall>
        </div>
      </div>
      <div v-else>
        <div v-if="waterfallList.length>0" class="mx-32rpx mt-20rpx">
          <s-waterfall :datalist="waterfallList" :column="2" @click="cancelMore">
            <template #default="{ item }">
              <div class="relative max-h-500rpx w-328rpx flex items-center justify-center overflow-hidden rounded-24rpx pr-32rpx">
                <image class="rounded-24rpx" lazy-load :src="item.imgUrl" mode="widthFix"
                       @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                <div v-if="item.article_type===2" class="absolute right-40rpx top-16rpx flex items-center justify-center">
                  <image :src="`${cdnUrl}/imgs/square/radio.png${imgVersion}`" mode="widthFix" class="w-60rpx"
                         @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                </div>
              </div>
              <div class="multiLine-hiddle mt-10rpx w-320rpx text-30rpx">
                {{ item.article_type===1?item.title:item.content }}
              </div>
              <div class="mb-22rpx w-320rpx flex items-center justify-between">
                <div class="flex items-center text-24rpx">
                  <image class="mr-15rpx h-36rpx w-36rpx rounded-50%" :src="item.avatar_url" mode="scaleToFill" />
                  <text>{{ item.nickname }}</text>
                </div>
                <div class="flex justify-center text-right text-hex-ABAFB5" @click.stop="handleClickMore(item)">
                  <image :src="`${cdnUrl}/imgs/square/more.png${imgVersion}`" mode="widthFix" class="h-48rpx w-48rpx" />
                </div>
              </div>
              <div v-show="currPoint === item.user_article__id && isShowPoint" class="relative">
                <div class="absolute bottom-80rpx left-0 z-99 box-border h-66rpx w-336rpx flex items-center justify-between rounded-lg bg-hex-fff px-16rpx text-hex-333"
                     style="box-shadow: 0 4px 20px 0 rgb(0 0 0 / 5%);">
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_like${isLike}.svg${imgVersion}`"
                         alt="" mode="scaleToFill" @click.stop="handleClickLike1(item)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_save${isCollect}.svg${imgVersion}`"
                         alt="" mode="scaleToFill" @click.stop="handleClickCollect1(item)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_msg.svg${imgVersion}`" mode="scalitemeToFill" alt=""
                         @click.stop="routerTo('/pages-square/articledetail', item.user_article__id)" />
                  <image class="h-44rpx w-44rpx"
                         :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" mode="scaleToFill" alt="" @click.stop="routerTo1('/pages-square/articledetail', item.user_article__id, true)" />
                </div>
              </div>
            </template>
          </s-waterfall>
        </div>
        <div v-if="waterfallList.length===0"
             class="mt-200rpx flex items-center justify-center">
          <div>
            <image
              class="h-364rpx w-364rpx"
              :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
              mode="scaleToFill"
            />
            <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
          </div>
        </div>
      </div>
    </div>

    <uni-popup ref="popup" type="bottom" background-color="#fff" class="z-999">
      <go-share class="z-99999" @close="closepop" />
    </uni-popup>
    <div class="h-167rpx">
      <tab-bar :is-show-text="true" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useLoginStore } from '@/stores/login'

let searchBarTop: any = $ref('24')
onLoad(() =>
{
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  uni.hideTabBar()
})
//生成小程序码
onShareAppMessage((res) => {
  return { title: '心悦' }
})
onShareTimeline(() => {
  return {
    title: '分享朋友圈',
  }
})
const loginStore = useLoginStore()
let currentTab = $ref(2)
let topList: any = $ref([])
const routerTo = (route, articleId) => {
  uni.navigateTo({
    url: `${route}?articleId=${articleId}`,
  })
}
const routerTo1 = (route, articleId, show) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  uni.navigateTo({
    url: `${route}?articleId=${articleId}&&showShare=${show}`,
  })
}

//栏目列表
let cloumnList: any = $ref([])
const getColumnList = async () => {
  const reqData = { method: 'get', headers: { timestamp: new Date().getTime() } }
  const { data, status, error } = await Fetch('/api/s/square/columnList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  cloumnList = data.result.dataList
}
//置顶
const getStickList = async () => {
  const reqData = {
    method: 'post',
    headers: { timestamp: new Date().getTime() },
  }
  const { data, status, error } = await Fetch('/api/s/square/stickList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  topList = data.result.dataList.slice(0, 3)
}
let currPoint = $ref(0)
let isShowPoint = $ref(false)
const handleClickMore = (item) => {
  if (currPoint === item.user_article__id) {
    isShowPoint = false
    currPoint = 0
    return
  }
  isShowPoint = true
  currPoint = item.user_article__id
  getSuggestMoreInfo(item)
}
let isLike = $ref(false) //是否点赞
let isCollect = $ref(false) //是否收藏
let attentionList: any = $ref([])
let attentionMore = $ref(false)
let pageNo1 = $ref(1)
const getAttentionList = async () => {
  const reqData = {
    method: 'get',
    data: {
      pageNo: pageNo1,
      pageSize: 2,
      columnId: 1,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/article/indexArticlePageList', reqData)
  attentionList = attentionList.concat(data.result?.dataList)
  if (attentionList.length < Number(data.result?.total)) {
    attentionMore = true
    return
  }
  attentionMore = false
}
let suggestList: any = $ref([])
let waterfallList: any = $ref([])
let baseData: any = $ref([])
let suggestMore = $ref(false)
let limit = $ref(8)
let offset = $ref(0)
const getSuggestList = async () => {
  const reqData = {
    method: 'post',
    headers: { timestamp: new Date().getTime() },
    data: {
      limit,
      offset,
      column_id: currentTab,
    },
  }
  const { data, status, error } = await Fetch('/api/s/square/recommendList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  baseData = data.result.dataList
  if (isNotNilOrEmpty(baseData)) {
    suggestList = suggestList.concat(baseData.map(e => {
      e.imgUrl = e.cover_image
      return e
    }))
  }
  waterfallList = clone(suggestList)
  if (suggestList.length < data.result.total) {
    suggestMore = true
    return
  }
  suggestMore = false
}
const getSuggestMoreInfo = async (item) => {
  const reqData = {
    method: 'get',
    data: {
      articleId: item.user_article__id,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/article/indexArticleStat', reqData)
  isLike = Boolean(data.result.isLike)
  isCollect = Boolean(data.result.isCollect)

}
//下滑加载更多数据
const getMoreData = () => {
  switch (currentTab) {
    case 1:
      if (attentionMore) {
        pageNo1++
        getAttentionList()
      }
      break
    case 2:
      if (suggestMore) {
        offset += limit
        getSuggestList()
      }
      break
  }
}
//关注列表：收藏,取消收藏
const handleClickCollect = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (item.isCollect) {
    case 0:
      await Fetch('/qqyapi/auth/collect/addCollect', reqData).then(res => {
        if (res.status === 200) {
          attentionList.forEach((currItem) => {
            if (currItem.id === item.id) {
              currItem.isCollect = 1
              currItem.collectCount += 1
            }
          })
        }
      })
      break
    case 1:
      await Fetch('/qqyapi/auth/collect/cancelCollect', reqData).then(res => {
        if (res.status === 200) {
          attentionList.forEach((currItem) => {
            if (currItem.id === item.id) {
              currItem.isCollect = 0
              currItem.collectCount -= 1
            }
          })
        }
      })
      break
  }
}
//关注列表：点赞,取消点赞
const handleClickLike = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (item.isLike) {
    case 0:
      await Fetch('/qqyapi/auth/article/like/addLike', reqData).then(res => {
        if (res.status === 200) {
          attentionList.forEach((currItem) => {
            if (currItem.id === item.id) {
              currItem.isLike = 1
              currItem.likeCount += 1
            }
          })
        }
      })
      break
    case 1:
      await Fetch('/qqyapi/auth/article/like/cancelLike', reqData).then(res => {
        if (res.status === 200) {
          attentionList.forEach((currItem) => {
            if (currItem.id === item.id) {
              currItem.isLike = 0
              currItem.likeCount -= 1
            }
          })
        }
      })
      break
  }
}
//推荐列表：收藏,取消收藏
const handleClickCollect1 = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.user_article__id,
    },
  }
  switch (isCollect) {
    case false:
      await Fetch('/qqyapi/auth/collect/addCollect', reqData).then(res => {
        if (res.status === 200) {
          getSuggestMoreInfo(item)
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/collect/cancelCollect', reqData).then(res => {
        if (res.status === 200) {
          getSuggestMoreInfo(item)
        }
      })
      break
  }
}
//推荐列表：点赞,取消点赞
const handleClickLike1 = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.user_article__id,
    },
  }
  switch (isLike) {
    case false:
      await Fetch('/qqyapi/auth/article/like/addLike', reqData).then(res => {
        if (res.status === 200) {
          getSuggestMoreInfo(item)
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/article/like/cancelLike', reqData).then(res => {
        if (res.status === 200) {
          getSuggestMoreInfo(item)
        }
      })
      break
  }
}
//取消展示更多组件
const cancelMore = () => {
  currPoint = 0
}



onShow(() => {
  // const refreshPage = uni.getStorageSync('refreshPage')
  // if (refreshPage) {
  //   uni.removeStorageSync('refreshPage') // 移除标记，防止下次误用
  //   suggestList = []
  //   limit = 8
  //   offset = 0
  //   getSuggestList()
  //   // 执行页面刷新逻辑
  // }
})
onMounted(() => {
  getColumnList()
  getStickList()
  getSuggestList()
  getAttentionList()
})
//监听页面滚动
onPageScroll(() => {
  cancelMore()
})
//触底加载更多数据
onReachBottom(() => {
  getMoreData()
})
const handTabClick = (item) => {
  currentTab = item.id
  suggestList = []
  waterfallList = []
  limit = 8
  offset = 0
  getSuggestList()


  // nextTick(() => {
  //   getSuggestList()
  // })
}
const popup: any = $ref(null)
const open = () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  popup.open('bottom')
}
const closepop = () => {
  popup.close()
}


</script>

<style lang="scss">
.square{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break:break-all;
  }



  // .bg-water{
  //   background: url('https://qqy-1254346585.cos.ap-nanjing.myqcloud.com/imgs/lazyload.gif') no-repeat center;
  //   background-size: 100%;
  // }
}

::-webkit-scrollbar{
  display: none;
}
</style>
